import React from 'react';
import { 
  Upload, 
  Button, 
  Typography,
  Alert,
  Space,
  message,
  Progress,
  Card,
  List
} from 'antd';
import { 
  LoadingOutlined,
  InboxOutlined,
  DeleteOutlined,
  MergeCellsOutlined,
  DragOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { pdfService } from '../services/pdfService';
import type { UploadProps } from 'antd';
import styles from './PDFMerger.module.css';
import PageHeader from './PageHeader';

const { Dragger } = Upload;
const { Title, Text } = Typography;

const PDFMerger: React.FC = () => {
  const [fileList, setFileList] = React.useState<File[]>([]);
  const [merging, setMerging] = React.useState(false);
  const [error, setError] = React.useState<string>('');
  const [progress, setProgress] = React.useState(0);
  const [mergedFile, setMergedFile] = React.useState<{
    blob: Blob;
    fileName: string;
  } | null>(null);

  const handleFileSelect = (info: any) => {
    const files = info.fileList.map((f: any) => f.originFileObj);
    
    setError('');
    setProgress(0);
    setMergedFile(null);

    // 验证文件
    const invalidFiles = files.filter((file: File) => !pdfService.validatePDFFile(file));
    if (invalidFiles.length > 0) {
      setError('请上传有效的PDF文件（每个文件小于50MB）');
      return;
    }

    setFileList(files);
  };

  const handleMerge = async () => {
    if (fileList.length < 2) {
      message.warning('请至少选择2个PDF文件');
      return;
    }

    try {
      setMerging(true);
      setError('');
      setProgress(0);
      setMergedFile(null);
      
      const response = await pdfService.mergePDFs(fileList);
      
      if (response.code === 200 && response.data?.blob && response.data?.fileName) {
        setProgress(100);
        setMergedFile({
          blob: response.data.blob,
          fileName: response.data.fileName
        });
        message.success('合并成功！');
      } else {
        throw new Error('合并失败，请重试');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '合并过程出错';
      setError(errorMessage);
      message.error('合并失败：' + errorMessage);
    } finally {
      setMerging(false);
    }
  };

  const handleDownload = async () => {
    if (!mergedFile) return;

    const hide = message.loading('准备保存...', 0);
    
    try {
      const success = await pdfService.saveFileWithDialog(
        mergedFile.blob, 
        mergedFile.fileName
      );

      hide();
      
      if (success) {
        message.success('文件保存成功');
      } else {
        message.info('已取消保存');
      }
    } catch (error) {
      hide();
      message.error('文件保存失败，请重试');
      console.error('Download error:', error);
    }
  };

  const uploadProps: UploadProps = {
    multiple: true,
    accept: '.pdf',
    showUploadList: false,
    beforeUpload: () => false,
    onChange: handleFileSelect,
  };

  return (
    <div className={styles.container}>
      <PageHeader title="合并PDF" />
      <Card className={styles.mergerCard}>
        <Title level={4} className={styles.cardTitle}>
          PDF文件合并
        </Title>

        <div className={styles.uploadSection}>
          <Dragger {...uploadProps} className={styles.draggerContainer}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined className={styles.uploadIcon} />
            </p>
            <p className={styles.uploadText}>
              点击或拖拽PDF文件到此区域
            </p>
            <p className={styles.uploadHint}>
              支持多个PDF文件，每个文件不超过50MB
            </p>
          </Dragger>
        </div>

        {fileList.length > 0 && (
          <div className={styles.fileList}>
            <List
              dataSource={fileList}
              renderItem={(file, index) => (
                <List.Item
                  className={styles.fileItem}
                  actions={[
                    <Button
                      key="delete"
                      icon={<DeleteOutlined />}
                      onClick={() => {
                        const newFiles = fileList.filter((_, i) => i !== index);
                        setFileList(newFiles);
                        if (newFiles.length === 0) {
                          setError('');
                          setProgress(0);
                          setMergedFile(null);
                        }
                      }}
                    >
                      删除
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<DragOutlined className={styles.fileIcon} />}
                    title={file.name}
                    description={`${(file.size / (1024 * 1024)).toFixed(2)}MB`}
                  />
                </List.Item>
              )}
            />

            <div className={styles.actionBar}>
              <Space>
                <Button
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setFileList([]);
                    setError('');
                    setProgress(0);
                    setMergedFile(null);
                  }}
                >
                  清空列表
                </Button>
                <Button
                  type="primary"
                  icon={merging ? <LoadingOutlined /> : <MergeCellsOutlined />}
                  onClick={handleMerge}
                  loading={merging}
                  disabled={fileList.length < 2 || !!error}
                >
                  {merging ? '合并中...' : '开始合并'}
                </Button>
              </Space>
            </div>
          </div>
        )}

        {error && (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            className={styles.alert}
          />
        )}

        {merging && (
          <div className={styles.progressContainer}>
            <Progress 
              percent={progress} 
              status={progress === 100 ? "success" : "active"}
              strokeColor={{
                '0%': '#108ee9',
                '100%': '#87d068',
              }}
            />
          </div>
        )}

        {mergedFile && (
          <Alert
            message={
              <Space size="middle" align="center" className={styles.mergedInfo}>
                <Text type="success">
                  文件已合并完成
                </Text>
                <Button 
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownload}
                >
                  保存文件
                </Button>
              </Space>
            }
            type="success"
            showIcon
          />
        )}
      </Card>
    </div>
  );
};

export default PDFMerger; 